package com.yhx.controller;

import com.yhx.utils.MessageConstant;
import com.yhx.utils.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("file")
public class FileController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Value("{spring.redis.pic}")
    private String pic;
    //将上传成功的图片保存到pic_list中
    public void saveFileimgname(String pic,String fileName){
        SetOperations<String, String> opsForSet = stringRedisTemplate.opsForSet();
        opsForSet.add(pic, fileName);
    }

    @RequestMapping("pic")    //用于测试
    public String upload(MultipartFile multipartFile){
        //上传文件的文件名
        String originalFilename = multipartFile.getOriginalFilename();
        //现在文件的名字
        String name = getName(originalFilename);
        try {
            multipartFile.transferTo(Paths.get("D:\\chrome下载\\" + name));
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        }
    }
    public String getName(String oldName){
        String format = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
        int i = oldName.lastIndexOf(".");
        //文件的后缀
        String substring = oldName.substring(i);
        //新文件名
        String newName=format+substring;
        return newName;
    }

    @Value("${upload.path}")
    private String path;
    @PostMapping("/uploadpic")
    public Result uploadpic(@RequestParam("imgFile") MultipartFile multipartFile){
        try {
            //改名字
            String name = getName(multipartFile.getOriginalFilename());
            //上传
            multipartFile.transferTo(new File(path+name));
            //将图片存入redis中
            saveFileimgname(pic,name);
            //返回名字用于回显
            return  new Result(true, MessageConstant.PIC_UPLOAD_SUCCESS,"/setmealpic/"+name);
        } catch (IOException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.PIC_UPLOAD_FAIL);
        }
    }
}
